package z.explorer.ui.component.walker;

import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.awt.*;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import z.explorer.Main;
import z.explorer.core.storage.TableMetaData;
import z.explorer.core.storage.dao.TableMetaDataDAO;
import z.explorer.ui.common.Handler;
import z.explorer.ui.common.ZTable;
import z.explorer.ui.common.ZTablePanel;

public class TableMetadata extends JPanel implements Handler {
	private static Log log = LogFactory.getLog(TableMetadata.class);

	private ZTablePanel zTablePanel = new ZTablePanel(null);
	
	private DetailPanel detailPanel = new DetailPanel(-1);
	
	private Configuration configuration = new Configuration();
	
	private History history = new History(-1);

	public TableMetadata() {
		init();
		loadData();
		initUI();
	}

	public void init(){
		ZTable ztable = zTablePanel.getZTable();
		ztable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){

			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				int rowIndex=zTablePanel.getZTable().getSelectedRow();
				int columnIndex=zTablePanel.getZTable().getzTableModel().getIndexByName("table_id");
				if(rowIndex==-1)
					return;
				Integer table_id=(Integer)zTablePanel.getZTable().getValueAt(rowIndex, columnIndex);
				detailPanel.setTable_id(table_id.intValue());
				detailPanel.loadData();
				history.setTable_id(table_id.intValue());
				history.loadData();
				configuration.setTableId(table_id);
			}});
	}
	
	public void initUI() {
		setLayout(new BorderLayout());
		add(zTablePanel, BorderLayout.CENTER);
	}

	public void loadData() {
		TableMetaDataDAO tableMetaDataDao = (TableMetaDataDAO) Main.context
				.getBean("tableMetaDataDAO");
		log.info("start to search metadata for table");
		List<TableMetaData> list = tableMetaDataDao.searchAll();
		zTablePanel.reloadData(list);
		log.info("end in searching metadata for table");
		
	}
	
	public DetailPanel getDetailPanel(){
		return detailPanel;
	}
	
	public Configuration getConfiguration(){
		return configuration;
	}
	
	public History getHistory(){
		return history;
	}
	
	@Override
	public String getMessage() {
		// TODO Auto-generated method stub
		return "loading the metadata for table ...";
	}

	@Override
	public void handle() {
		// TODO Auto-generated method stub
		loadData();
	}

}
